package com.bristua.mall.wx.controller;

import com.bristua.mall.common.utils.CommonTools;
import com.bristua.mall.common.utils.JsonUtil;
import com.bristua.mall.order.biz.WxAppPayOrderAsyncCallbackBiz;
import com.bristua.mall.user.biz.WxAppChargeVipAsyncCallbackBiz;
import com.bristua.mall.wx.model.WXConfig;
import com.bristua.mall.wx.util.WXPayConstants;
import com.bristua.mall.wx.util.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by Administrator on 2019/4/19.
 */
@RestController
public class AppWxPayCallbackController {
    private static final Logger logger = LoggerFactory.getLogger(AppWxPayCallbackController.class);

    @Autowired
    private WXConfig wxConfig;

    @Autowired
    private WxAppPayOrderAsyncCallbackBiz wxAppPayOrderAsyncCallbackBiz;

    @Autowired
    private WxAppChargeVipAsyncCallbackBiz wxAppChargeVipAsyncCallbackBiz;

    @RequestMapping("/wx/app/pay/notify")
    public String appWxPayCallbck(HttpServletRequest request, HttpServletResponse response){
        ServletInputStream in = null;
        try {
            in = request.getInputStream();
            String xmlMsg = CommonTools.inputStream2String(in);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xmlMsg);
            logger.info("微信APP支付回调通知参数:" + JsonUtil.toJson(notifyMap));
            //支付是否成功
            if (notifyMap == null || !notifyMap.get("result_code").equals("SUCCESS") || !notifyMap.get("return_code").equals("SUCCESS")) {
                logger.info("微信支付通知失败");
                return WXPayConstants.RETURN_FAIL;
            }
            if (!WXPayUtil.isSignatureValid(notifyMap, wxConfig.getKey())) {
                logger.error("微信支付通知验证签名失败");
                return WXPayConstants.VALIDATE_FAIL;
            }
            String attach = notifyMap.get("attach");

            if("vip".equals(attach)){
                wxAppChargeVipAsyncCallbackBiz.chargeVipAsyncCallback(notifyMap);
            }else{
                wxAppPayOrderAsyncCallbackBiz.updateOrderPayStatus(notifyMap);
            }

            return WXPayConstants.RETURN_SUCCESS;

        }catch (Exception ex){

        }

        return null;
    }
}
